from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
from datetime import datetime
from sqlalchemy.orm import relationship
from commons.database import Base


class Category(Base):
    """
    商品分类模型，支持层级结构，通过parent_id实现级联查询
    """
    __tablename__ = "categories"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="分类ID")
    name = Column(String(50), nullable=False, comment="分类名称")
    parent_id = Column(Integer, ForeignKey("categories.id", ondelete="SET NULL"), nullable=True, comment="父分类ID，顶级分类为NULL")
    description = Column(Text, comment="分类描述")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")

    # 自引用关系：一个分类可以有多个子分类
    children = relationship(
        "Category",
        back_populates="parent",
        cascade="all, delete-orphan",
        passive_deletes=True
    )
    # 父分类引用
    parent = relationship(
        "Category",
        back_populates="children",
        remote_side=[id]
    )

    def to_dict(self, include_children=False):
        """
        将分类对象转换为字典，支持包含子分类
        :param include_children: 是否包含子分类
        :return: 分类字典
        """
        data = {
            "id": self.id,
            "name": self.name,
            "parent_id": self.parent_id,
            "description": self.description,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }
        if include_children:
            data["children"] = [child.to_dict(include_children=True) for child in self.children]
        return data